{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fff96f59",
   "metadata": {},
   "source": [
    "# 百度AI开放平台"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ae06199",
   "metadata": {},
   "source": [
    "## 通用物体和场景识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2cc1e7",
   "metadata": {},
   "source": [
    "* 接口描述                                                                                                               \n",
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "\n",
    "* 请求示例                                                                      \n",
    "> HTTP 方法：POST\n",
    "\n",
    "* 请求URL                                                                   \n",
    "> https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c42431a3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.dbb6529172c363df33aadaa3de1263ae.315360000.1965126309.282335-25869197', 'expires_in': 2592000, 'session_key': '9mzdDce9vbS9Pg51fpf6KcvfpAa1FVtTDjzf47e9bSl2R1f8BtpFj6E+ZC+aoKnZyLWgHfOtlX9SBrvQH/DgLNO0oVMZGg==', 'access_token': '24.61d2454aee5f86d39f0cda303ca88b63.2592000.1652358309.282335-25869197', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '3cfdc0ec7baaa652fce1ab159d8d903f'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'3Yrg2XEiwA0EPgUkdBwc7QeZ',\n",
    "    'client_secret':'qbdSrE0BT6FbPeDEh6I9XudbiQyrpMrC'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())\n",
    "    access_token = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "978174c2",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.61d2454aee5f86d39f0cda303ca88b63.2592000.1652358309.282335-25869197'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4c0c203a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "58b32892",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b1f14358",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '海洋', 'score': 0.783014, 'root': '自然风景-海洋'}, {'keyword': '湖泊', 'score': 0.618497, 'root': '自然风景-湖泊'}, {'keyword': '港口码头', 'score': 0.451519, 'root': '建筑-现代建筑'}, {'keyword': '江河', 'score': 0.238479, 'root': '自然风景-江河'}, {'keyword': '天空', 'score': 0.054879, 'root': '自然风景-天空'}], 'log_id': 1513855768043057696}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# #绝对路径\n",
    "# f = open('C:/Users/86181/Desktop/大多文件/课程/2021-2022第二学期课程/api/xihu.jpg', 'rb')\n",
    "# #相对路径\n",
    "f = open('xihu.jpg','rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 写url的参数(酬载)\n",
    "payload = {\n",
    "    'access_token':access_token,\n",
    "    'image':img\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, params=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c3ae5bb3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '154', 'has_calorie': True, 'name': '鱼香肉丝', 'probability': '0.949881', 'baike_info': {}}, {'calorie': '147', 'has_calorie': True, 'name': '炒面', 'probability': '0.0133961', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%82%92%E9%9D%A2/3102837', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/738b4710b912c8fc50a5ea67f1039245d78821c1', 'description': '炒面是流行于大江南北的中国传统小吃，制作原料主要有面条、鸡蛋、肉丝、小油菜、葱段等，口味鲜美，营养丰富。一般是指两种，一种是炒面条，另一种是炒面粉。炒面条是以面条、鸡蛋或肉为主要食材的面食。在中国，炒面主要有：广州的豉油皇炒面、漯河的炒面、安庆的炒面、芜湖的炒面、辽宁的炒面、潮汕干炒面、山东拌炒面。炒面粉是将玉米、豆子等炒熟磨成的面，这样在食用的时候用热的汤水一冲或搅拌就可以食用。'}}, {'calorie': '240', 'has_calorie': True, 'name': '酱肉丝', 'probability': '0.0108926', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%85%B1%E8%82%89%E4%B8%9D/2689787', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b90e7bec54e736d1fb1014b39b504fc2d562690e', 'description': '酱肉丝是一道传统的家常菜，主要制作食材是猪里脊肉，配料是豆腐皮等，调料是甜面酱、白糖、料酒等，通过大火烧制而成。'}}, {'calorie': '268', 'has_calorie': True, 'name': '肉丝饭', 'probability': '0.0100035', 'baike_info': {}}, {'has_calorie': False, 'name': '盖浇饭', 'probability': '0.0036003', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%9B%96%E6%B5%87%E9%A5%AD/1192126', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/3c6d55fbb2fb43166d2207bff6ec512309f791527597', 'description': '盖浇饭是一种古老的汉族小吃。属于西北甘肃地区叫法，东北叫盖饭，广东叫碟头饭，还有的地方只是叫咖喱土豆饭，咖喱鸡饭，麻婆豆腐饭，以此类推这样子，其实都是菜和饭放在一个盘子里吃，菜浇在饭上，由此称作盖浇饭。其特点饭菜结合、快而热。而风俗各别，如今的盖浇饭，各地作法也不一样，用料也不同，所以也各有特色。'}}], 'log_id': 1513855770451820440}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('yuxiangrousi.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "\n",
    "access_token = '24.3cf7dca666cd533e66e703c9d61f1048.2592000.1652243080.282335-25869197'\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "251a4c25",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'name': '樱桃李', 'score': 0.19379164}, {'name': '梨花', 'score': 0.16659872}, {'name': '杜梨', 'score': 0.11254661}], 'log_id': 1513375709301245454}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('lihua.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.3cf7dca666cd533e66e703c9d61f1048.2592000.1652243080.282335-25869197'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a97fec65",
   "metadata": {},
   "source": [
    "作业:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f63c576",
   "metadata": {},
   "source": [
    "用户需求分析:                                       \n",
    "   我相信有不少人，会在网上看到一些景点但是不知道在哪。                                      \n",
    "   如果说，有一款根据图片搜索地标的应用，那岂不是简单快捷？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "7ebcdb51",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "导入景点图片jpg文件xihu.jpg\n"
     ]
    }
   ],
   "source": [
    "picture = input(\"导入景点图片jpg文件\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "2f1c0ed1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': {'landmark': ''}, 'log_id': 1513396902806489905}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "地标识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/landmark\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open(picture, 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.3cf7dca666cd533e66e703c9d61f1048.2592000.1652243080.282335-25869197'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e860668",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
